package hoowin.app.wsnd.dao.springImp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import hoowin.app.wsnd.dao.ITranslationDao;
import hoowin.app.wsnd.model.Translation;
import hoowin.basic.util.Trans;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class TranslationDao extends JdbcDaoSupport implements ITranslationDao {

	@Override
	public Translation getTranslationById(int id) {
		String sql = "select * from apps_wsnd_translations where id="+id;
		return (Translation)super.getJdbcTemplate().queryForObject(sql, new TranslationRowMapper());
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List getTranslationListByStatusId(int statusId) {
		String sql = "select * from apps_wsnd_translations where to_status="+statusId;
		return super.getJdbcTemplate().query(sql, new TranslationRowMapper());
	}

	@Override
	public int addTranslation(Translation translation) {
		String sql = "insert into apps_wsnd_translations (id, publisher, language, publish_time, content, to_status) values (null, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, translation.getPublisherId(), translation.getLanguage(), Trans.dateToString(new Date()), translation.getContent(), translation.getStatusId())>0){
			return super.getJdbcTemplate().queryForInt("select last_insert_id()");
		}else return 0;
	}

	@Override
	public boolean deleteTranslationById(int id) {
		if(super.getJdbcTemplate().update("delete from apps_wsnd_translations where id="+id)>0)return true;
		return false;
	}
	
	class TranslationRowMapper implements RowMapper<Object>{

		@Override
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			Translation translation = new Translation();
			translation.setId(rs.getInt("id"));
			translation.setPublisherId(rs.getInt("publisher"));
			translation.setLanguage(rs.getString("language"));
			translation.setPublishTime(Trans.stringToDate(rs.getString("publish_time")));
			translation.setStatusId(rs.getInt("to_status"));
			translation.setContent(rs.getString("content"));
			return translation;
		}
	}

	@Override
	public boolean deleteTranslationsByStatusId(int statusId) {
		if(super.getJdbcTemplate().update("delete from apps_wsnd_translations where to_status="+statusId)>0)return true;
		return false;
	}
}
